package com.system.travel.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.travel.common.exception.BusinessException;
import com.system.travel.common.exception.ErrorCode;
import com.system.travel.modules.system.entity.SysPermission;
import com.system.travel.modules.system.mapper.SysPermissionMapper;
import com.system.travel.modules.system.service.SysPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统权限Service实现类
 *
 * @author lucas
 * @date 2024/01/01
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Override
    public List<SysPermission> getPermissionsByRoleId(Long roleId) {
        return baseMapper.selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<SysPermission> getPermissionsByUserId(Long userId) {
        return baseMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public List<SysPermission> getMenuList() {
        return baseMapper.selectMenuList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long permissionId, Integer status) {
        // 获取权限信息
        SysPermission permission = getById(permissionId);
        if (permission == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND);
        }

        // 更新状态
        permission.setStatus(status);
        updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVisible(Long permissionId, Integer visible) {
        // 获取权限信息
        SysPermission permission = getById(permissionId);
        if (permission == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND);
        }

        // 更新可见性
        permission.setVisible(visible);
        updateById(permission);
    }

    @Override
    public List<SysPermission> buildPermissionTree(List<SysPermission> permissions) {
        // 构建树形结构
        Map<Long, List<SysPermission>> childrenMap = permissions.stream()
                .filter(permission -> permission.getParentId() != null && permission.getParentId() != 0)
                .collect(Collectors.groupingBy(SysPermission::getParentId));

        permissions.forEach(permission -> permission.setChildren(childrenMap.get(permission.getId())));

        return permissions.stream()
                .filter(permission -> permission.getParentId() == null || permission.getParentId() == 0)
                .collect(Collectors.toList());
    }
} 